import {
  createSlice,
  createAsyncThunk
} from '@reduxjs/toolkit'

import {
  getMovieListRequset
} from '../../api/index'

// 异步 action {type: 'getMovieList/fulfilled', 函数返回值}
export const getMovieListAction = createAsyncThunk('getMovieList', async (data, store) => {
  try {
    const {
      data
    } = await getMovieListRequset()
    return data.list
  } catch (error) {
    alert(error)
    return store.getState().movieList
  }
})

const movieSlice = createSlice({
  name: 'movie',
  initialState: {
    movieList: []
  },
  extraReducers: {
    [getMovieListAction.fulfilled](state, {payload}) {
      state.movieList = payload
    },
    [getMovieListAction.rejected](state, error) {
      alert(error)
    },
    [getMovieListAction.pending](state) {
      console.log('getMovieListAction -- pending');
    },
  }
})

export default movieSlice.reducer